package org.boot.thread.service.impl;

import org.boot.thread.service.ThreadService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;

/**
 * {@link ThreadService} 接口默认实现类
 *
 * @author 李坤
 * @date 2022/8/19 9:21
 */
@Service("threadService")
public class ThreadServiceImpl implements ThreadService {

    // 日志处理器
    private final Logger logger = LoggerFactory.getLogger(ThreadService.class);

    @Resource
    private ThreadPoolTaskExecutor defaultExecutor;
    @Resource
    private ThreadPoolTaskExecutor noQueueCapacityExecutor;

    @Override
    public Future<Boolean> verityThreadPool() {
        boolean result = true;
        final long time = ThreadLocalRandom.current().nextLong(3000L);
        logger.info("逻辑处理耗时: {}毫秒", time);
        try {
            Thread.sleep(time);
        } catch (InterruptedException exception) {
            logger.error("处理业务逻辑出现异常");
            result = false;
        } finally {
            logger.info("当前线程池线程数: {}", noQueueCapacityExecutor.getPoolSize());
            logger.info("当前线程池活动线程数: {}", noQueueCapacityExecutor.getActiveCount());
        }
        return new AsyncResult<>(result);
    }

}
